﻿using Microsoft.Xaml.Behaviors;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Xcj.Mes.WholeLine.ZH.HG.Shell.Common
{
    public class WatermarkBehavior : Behavior<TextBox>
    {
        public static readonly DependencyProperty WatermarkTextProperty =
            DependencyProperty.Register("WatermarkText", typeof(string), typeof(WatermarkBehavior));

        public string WatermarkText
        {
            get => (string)GetValue(WatermarkTextProperty);
            set => SetValue(WatermarkTextProperty, value);
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.GotFocus += RemoveWatermark;
            AssociatedObject.LostFocus += ShowWatermark;
            ShowWatermark(null, null); // 初始显示水印
        }

        private void RemoveWatermark(object sender, RoutedEventArgs e)
        {
            if (AssociatedObject.Text == WatermarkText)
            {
                AssociatedObject.Text = "";
                AssociatedObject.Foreground = Brushes.Black;
            }
        }

        private void ShowWatermark(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(AssociatedObject.Text))
            {
                AssociatedObject.Text = WatermarkText;
                AssociatedObject.Foreground = Brushes.Gray;
                AssociatedObject.VerticalAlignment = VerticalAlignment.Center;
                AssociatedObject.VerticalContentAlignment = VerticalAlignment.Center;
                AssociatedObject.FontWeight = FontWeights.Light;
            }
        }

        protected override void OnDetaching()
        {
            AssociatedObject.GotFocus -= RemoveWatermark;
            AssociatedObject.LostFocus -= ShowWatermark;
            base.OnDetaching();
        }
    }
}
